﻿using AutoMapper;
using MediatR;
using Process.Api.Application.Command.BOM;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler.BOM
{
    public class AddGoodsinfoHandler : IRequestHandler<AddGoodsinfoCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<Goodsinfo> goodsinfoRepo;
        private readonly IMapper mapper;

        public AddGoodsinfoHandler(IProcessRepository<Goodsinfo> goodsinfoRepo, IMapper mapper)
        {
            this.goodsinfoRepo = goodsinfoRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(AddGoodsinfoCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            var model =mapper.Map<Goodsinfo>(request);
            model.CreateTime=DateTime.Now;
            model.Creater = "张三";

            var list = goodsinfoRepo.GetAllAsync().FirstOrDefault(x => x.GoodsCode == request.GoodsCode);
            if (list!=null)
            {
                result.Code = ErrorStatus.Error;
                result.Message = "物品编号已存在";
                return result;
            }
            var res = goodsinfoRepo.CreateAsync(model).Result;
            if (res>0)
            {
                result.Code = ErrorStatus.Success;
                result.Message = "添加物品信息成功";
                result.Data = res;
            }
            else
            {
                result.Code = ErrorStatus.Error;
                result.Message = "添加物品信息失败";
                result.Data = res;
            }
            return result;
        }
    }
}
